<template>
  <view v-show="show" class="canvas-area-wrap">
    <view class="canvas-area">
      <view class="canvas clock-sign" :class="canvasClass">
        <canvas class="class" :canvas-id="canvasId" />
        <image
          :show-menu-by-longpress="true"
          :src="tempFilePath"
          @touchcancel="touchcancel"
          @touchstart="gtouchstart"
          @touchmove="gtouchmove"
          @touchend="gtouchend"
        />
      </view>
      <view v-show="hasSign" class="canvas-area__close" @tap="close">
        <image :lazy-load="true" :src="CLOSED" />
      </view>
    </view>

    <view v-show="hasSign" class="canvas-operation">
      <image :src="LONG_TIME_PRESS_ICON" />
    </view>
  </view>
</template>

<script>
import Taro from "@tarojs/taro"
import mixins from './mixins'
import {
  USER_IMG,
  QR_CODE,
  RIGHT_ARROWS,
  CLOCK_SIGN_BGI,
  CLOCK_OVER_BGI,
  CLOCK_OVER_NUMBER_BOX,
  CLOSED,
  OVER_SIGN,
  CLOCK_SIGN,
  CLOCK_SIGN_CLASS,
  SAVE_ICON,
  LONG_TIME_PRESS_ICON
} from '@/config/clock-in'
import { getPoster } from '_api/clock-detail'

import {
  SCREENSHOT_WIDTH
} from '@/config/component-config/generate-image'
import { IMAGE_CDN } from "@/config/index.ts";
/* 打卡日签白色背景 */
const CLOCL_SIGN_WHITE_BGI = 'https://xthk-edu-test.oss-cn-shenzhen.aliyuncs.com/1610334571212_0.437958233450759'
/* 完结日签白色背景 */
const OVER_CLOCL_SIGN_WHITE_BGI = 'https://xthk-edu-test.oss-cn-shenzhen.aliyuncs.com/1610334685995_0.40462992037645207'

export default {
  mixins: [mixins],
  props: {
    themeId: {
      type: [Number, String],
      default: 0
    },
    show: {
      type: Boolean,
      default: false
    },
    canvasId: {
      type: String,
      default: 'poster'
    },
    uuid: {
      type: String,
      default: '',
      required: true,
    },
    studentId: {
      type: [String, Number],
      default: '',
      required: true,
    }
  },
  data () {
    return {
      CLOSED,
      SAVE_ICON,
      LONG_TIME_PRESS_ICON,
      /* 保存图片时暂存的图片虚拟路路径 */
      tempFilePath: '',
      /* 打卡日签canvas数据 */
      daySignCanvasData: [],
      dkOverCanvasData: [],
      type: 0,
      /* 隐藏分享和关闭按钮 */
      hasSign: false,
    }
  },
  computed: {
    canvasClass () {
      return CLOCK_SIGN_CLASS[this.type]
    }
  },
  watch: {
    show (n, o) {
      console.log(n, 'nnnnnnn')
      n && this.getPoster()
      if (!n) {
        this.tempFilePath = ''
        Taro.hideLoading()
      }
    }
  },
  methods: {

    /* 获取日签信息 */
    async getPoster () {
      if (!this.uuid) {
        console.log('getPostergetPostergetPoster')
        this.$emit('update:show', false)
        /* 防止页面关闭时toast随之关闭 */
        setTimeout(() => {
          Taro.showToast({ title: "今日未打卡，打卡后才能生成日签哦", icon: 'none', duration: 2000 })
        }, 200)
        return
      }
      Taro.showLoading({ title: "海报加载中", icon: 'none' })
      const { data } = await getPoster({ student_id: this.studentId, uuid: this.uuid }).catch(error => {
        this.$emit('update:show', false)

        Taro.hideLoading()
        if (error.status_code === 4001) {
          this.$emit('activeBreakRule', error)
        }
        return { data: null }
      })
      if (data) {

        this.posterData = data
        this.type = data.type
        /* 判断是打卡日签 还是完结日签 */
        this.type === CLOCK_SIGN ? this.clockDaySignImage() : this.clockDaySignOverImage()
      }
    },
    /* 绘制圆角矩形 */
    drawRoundRect (cxt, x, y, width, height, radius) {
      cxt.beginPath()
      cxt.arc(x + radius, y + radius, radius, Math.PI, Math.PI * 3 / 2)
      cxt.lineTo(width - radius + x, y)
      cxt.arc(width - radius + x, radius + y, radius, Math.PI * 3 / 2, Math.PI * 2)
      cxt.lineTo(width + x, height + y - radius)
      cxt.arc(width - radius + x, height - radius + y, radius, 0, Math.PI * 1 / 2)
      cxt.lineTo(radius + x, height + y)
      cxt.arc(radius + x, height - radius + y, radius, Math.PI * 1 / 2, Math.PI)
      cxt.closePath()
    },
    /* 生成打卡完结日签图 */
    clockDaySignOverImage () {
      let that = this
      const { qr_code, student_avatar, student_name, share_str, last_day: { clock_end_img, clock_num, continuous_clock_num, best_rank, praise_num, clock_end_title, activity_title } } = this.posterData
      this.dkOverCanvasData = [
        { type: 'image', value: clock_end_img, dWidth: SCREENSHOT_WIDTH, dHeight: 950 },
        { type: 'image', value: OVER_CLOCL_SIGN_WHITE_BGI, position: [24, 40], dWidth: 596, dHeight: 878 },
        { type: 'image', value: student_avatar, position: [282, 156], dWidth: 80, dHeight: 80, radius: true },
        { type: 'text', value: student_name, position: [266, 252], fontSize: 28, color: '#303133', centerX: true },
        { type: 'text', value: activity_title, position: [233, 340], fontSize: 36, color: '#303133', centerX: true, lineFeed: true, lineFeedWidth: 532, lineHeight: 48 },
        { type: 'text', value: clock_end_title, position: [98, 436], fontSize: 28, color: '#909399', centerX: true },
        { type: 'image', value: CLOCK_OVER_NUMBER_BOX, position: [56, 492] },
        { type: 'image', value: CLOCK_OVER_NUMBER_BOX, position: [202, 492] },
        { type: 'image', value: CLOCK_OVER_NUMBER_BOX, position: [346, 492] },
        { type: 'image', value: CLOCK_OVER_NUMBER_BOX, position: [492, 492] },
        { type: 'text', value: '打卡次数', position: [60, 596], fontSize: 24, color: '#909399' },
        { type: 'text', value: clock_num, position: [56, 520], fontSize: 28, color: '#333333', centerX: true, centerWidth: 96 },
        { type: 'text', value: '连续打卡', position: [202, 596], fontSize: 24, color: '#909399' },
        { type: 'text', value: continuous_clock_num, position: [202, 520], fontSize: 28, color: '#333333', centerX: true, centerWidth: 96 },
        { type: 'text', value: '最佳排行', position: [346, 596], fontSize: 24, color: '#909399' },
        { type: 'text', value: best_rank, position: [346, 520], fontSize: 28, color: '#333333', centerX: true, centerWidth: 96 },
        { type: 'text', value: '收获点赞', position: [492, 596], fontSize: 24, color: '#909399' },
        { type: 'text', value: praise_num, position: [492, 520], fontSize: 28, color: '#333333', centerX: true, centerWidth: 96 },
        { type: 'text', value: '查看TA的打卡作品', position: [60, 818], fontSize: 32, color: '#303133' },
        { type: 'text', value: '长按扫码关注心田花开服务号', position: [60, 758], fontSize: 24, color: '#303133' },
        { type: 'image', value: qr_code, position: [436, 726], dWidth: 160, dHeight: 160 },
        { type: 'image', value: RIGHT_ARROWS, position: [384, 764] },
      ]
      this.drawCanvas(this.dkOverCanvasData,
        function (cvsCtx) {
          console.log('sauidfasydvksudguiasvd uj')
          that.drawRoundRect(cvsCtx, 48, (750) - 1, 366, 50, 24)
          cvsCtx.fillStyle = '#FFF9DE'
          cvsCtx.fill()
        })
    },
    /* 生成打卡日签图 */
    clockDaySignImage () {
      let that = this
      let { qr_code, student_avatar, student_name, share_str, day: { title, day_sign_img, total_clock_num, total_clock_num_rank, created_at_Ym, created_at_d } } = this.posterData
      /* > 100 : 418 */
      /* > 10 : 427 */
      /* >0 : 440 */
      total_clock_num_rank = 1
      let totalClockNumRankPositionX
      if (total_clock_num_rank) {
        total_clock_num_rank < 100 && (totalClockNumRankPositionX = 427)
        total_clock_num_rank < 10 && (totalClockNumRankPositionX = 440)
        total_clock_num_rank >= 100 && (totalClockNumRankPositionX = 418)
      } else {
        totalClockNumRankPositionX = 440
      }
      this.daySignCanvasData = [
        { type: 'image', value: day_sign_img, dWidth: SCREENSHOT_WIDTH, dHeight: 860 },
        { type: 'image', value: CLOCL_SIGN_WHITE_BGI, position: [24, 40], dWidth: 596, dHeight: 788 },
        /* 签到天数 */
        { type: 'text', value: created_at_d, position: [174, 51], fontSize: 60, color: '#303133', centerX: true, centerWidth: 108 },
        /* 签到日期 */
        { type: 'text', value: created_at_Ym, position: [330, 64], fontSize: 36, color: '#303133' },
        /* 头像 */
        { type: 'image', value: student_avatar, position: [56, 206], dWidth: 80, dHeight: 80, radius: true },
        /* 名字  */
        { type: 'text', value: student_name, position: [160, 226], fontSize: 28, color: '#303133' },
        { type: 'text', value: '我在', position: [56, 308], fontSize: 32, color: '#909399' },
        /* 战队名称 */
        { type: 'text', value: `「${title}」`, position: [120, 308], fontSize: 32, color: '#303133', lineFeed: true, lineFeedX: 56, lineFeedSecondWidth: 545, lineFeedWidth: 480, lineHeight: 48 },

        { type: 'text', value: '坚持打卡', position: [124, 460], fontSize: 24, color: '#999999' },
        /* { type: 'text', value: '天', position: [170, 504], fontSize: 28, color: '#303133' }, */
        { type: 'text', value: '排行', position: [448, 460], fontSize: 24, color: '#999999' },

        { type: 'text', value: total_clock_num + '天', position: [124, 498], fontSize: 36, color: '#303133', centerX: true, centerWidth: 96 },
        /* 排行位数 */
        { type: 'text', value: total_clock_num_rank || '-', position: [totalClockNumRankPositionX, 496], fontSize: 36, color: '#303133', centerX: true, centerWidth: 64 },
        { type: 'text', value: '查看TA的打卡作品', position: [60, 728], fontSize: 32, color: '#303133' },
        { type: 'text', value: '长按扫码关注心田花开服务号', position: [60, 668], fontSize: 24, color: '#303133' },
        { type: 'image', value: qr_code, position: [436, 636], dWidth: 160, dHeight: 160 },
        { type: 'image', value: RIGHT_ARROWS, position: [384, 674] },
      ]
      this.drawCanvas(this.daySignCanvasData,
        function (cvsCtx) {
          console.log('sauidfasydvksudguiasvd uj')
          that.drawRoundRect(cvsCtx, 48, (660) - 1, 366, 50, 24)
          cvsCtx.fillStyle = '#FFF9DE'
          cvsCtx.fill()
        }
      )
    },
    canvasToImage () {
      console.log('开始生成图片')
      Taro.canvasToTempFilePath({ // 调用小程序API对canvas转换成图
        x: 0, // 开始截取的X轴
        y: 0, // 开始截取的Y轴
        width: SCREENSHOT_WIDTH, // 开始截取宽度
        height: this.type === OVER_SIGN ? 950 : 860,  // 开始截取高度
        destWidth: SCREENSHOT_WIDTH * 2,  // 截取后图片的宽度（避免图片过于模糊，建议2倍于截取宽度）
        destHeight: (this.type === OVER_SIGN ? 950 : 860) * 2, // 截取后图片的高度（避免图片过于模糊，建议2倍于截取宽度）
        canvasId: this.canvasId, // 截取的canvas对象
        success: (res) => { // 转换成功生成临时链接并调用保存方法
          this.tempFilePath = res.tempFilePath
          this.hasSign = true
          /* console.log(this.tempFilePath, 'this.tempFilePath') */
        },
        fail: function (res) {
          console.log(res)
        },
        complete: function () {
          Taro.hideLoading()
        }
      }, this.$scope)
    },
  }
}
</script>
<style lang="scss" >
@import "./index.scss";
.canvas-area {
  .canvas.clock-sign {
    height: 860px;
  }
  .canvas.overSign {
    height: 950px !important;
  }
}
</style>

